import './style.scss'
import { useEffect, useRef, useState } from 'react';
import { useNavigate, Link,useParams } from 'react-router-dom';
import type { ResponseType } from './types';
import useRequest from '../../hooks/useRequest';
// 获取缓存的location经纬度
const localLocation = localStorage.getItem('location');
const locationHistory = localLocation ? JSON.parse(localLocation) : null;
// 默认请求数据
const defaultRequestData = {
  url: '/hot-search-list.json',
  method: 'GET',
  params: {shopId: ''}
}
const Search = () => {
  const localSearchList = localStorage.getItem('search-list');
  const searchListHistory: string[] = localSearchList ? JSON.parse(localSearchList) : [];
  const [keyword, setKeyword] = useState('');
  const navigate = useNavigate();
  const params = useParams<{shopId:string}>(); // 它可以获取到url上面的参数
  if(params.shopId){
    defaultRequestData.params.shopId = params.shopId;
  }
  const [historyList, setHistoryList] = useState(searchListHistory);
  const { data } = useRequest<ResponseType>(defaultRequestData);
  const hotList = data?.data || [];
  function handleKeyDown (key: string){
    if(key === 'Enter' && keyword){
      const keywordIndex = historyList.findIndex(item => item === keyword);
      console.log('keywordIndex=', keywordIndex);
      const newHistoryList = [...historyList];
      if(keywordIndex > -1){
        newHistoryList.splice(keywordIndex, 1)
      }
      newHistoryList.unshift(keyword);
      if (newHistoryList.length > 20){
        newHistoryList.length = 20
      }
      setHistoryList(newHistoryList);
      localStorage.setItem('search-list', JSON.stringify(newHistoryList));
      navigate(`/searchlist/${params.shopId}/${keyword}`);
      setKeyword('');
    }
  }
  function handleHistoryListClean(){
    setHistoryList([]);
    localStorage.setItem('search-list', JSON.stringify([]));
  }
  function handleKeyWordClick(keyword:string){
    navigate(`/searchlist/${params.shopId}/${keyword}`);
  }
  return (
    <div className="page search-page">
      <div className="search">
        <Link to='/home' className='search-back-link'>
          <div className="iconfont search-back-icon">&#xe600;</div>
        </Link>
        <div className="search-area">
          <div className="iconfont search-icon">&#xe6c5;</div>
          <input type="text" 
            className="search-input" 
            placeholder='请输入商品名称' 
            value={keyword} 
            onChange={e=>{setKeyword(e.target.value)}}
            onKeyDown={e=>{handleKeyDown(e.key)}}
           />
        </div>
      </div>
      {
        historyList.length ? (
          <>
            <div className="title">历史搜索
              <div className="iconfont title-close"
              onClick={handleHistoryListClean}>&#xe62b;</div>
            </div>
            <ul className="list">
              {
                historyList.map((item, index)=>{
                  return (
                    <li className="list-item" key={item+index} onClick={()=>{handleKeyWordClick(item)}}>{item}</li>
                  )
                })
              }
            </ul>
          </>
        ) : null
      }
      <ul className="list">
      {
        hotList.length ? (
          <>
            <div className="title">热门搜索</div>
            <ul className="list">
              {
                hotList.map((item, index)=>{
                  return <li className="list-item" key={item.id} onClick={()=>{handleKeyWordClick(item.keyword)}}>{item.keyword}</li>
                })
              }
            </ul>
          </>
        ) : null
      }
      </ul>
    </div>
  )
}

export default Search;